const image = document.getElementById('image');
const cropper = new Cropper(image, {
  aspectRatio: 16 / 9,
  viewMode: 1,
  crop(event) {

  },
});


document.getElementById('file-up').onchange = function (e) {
  const files = e.target.files;
  let postFiles = Array.prototype.slice.call(files);
  postFiles = postFiles.slice(0, 1);

  if (postFiles.length === 0) return;

  let file = postFiles[0]

  if (!file) {
    return;
  }

  const reader = new FileReader()

  reader.readAsDataURL(file)
  reader.onload = (event) => {
    cropper.replace(event.srcElement.result)
  }
}

document.getElementById('preview-img-btn').onclick = function (e) {
  let innerHTML = e.target.innerHTML
  switch (innerHTML) {
    case '本地上传' :
      document.getElementById('file-up').click()
      break
    case '预览' :
      let viewElm = document.querySelector(".img-action-wrap .cropper-container .cropper-modal")

      if (!viewElm) return

      if (!viewElm.style.opacity || Number(viewElm.style.opacity) === 0.5) {
        e.target.classList.add("active");
        viewElm.style.opacity = 0.9
      } else {
        e.target.classList.remove("active");
        viewElm.style.opacity = 0.5
      }
      break
  }
}

document.getElementById('base-img-btn').onclick = function (e) {
  let innerHTML = e.target.innerHTML
  switch (innerHTML) {
    case '旋转' :
      cropper.rotate(90)
      break
    case '缩小' :
      cropper.zoom(-0.1)
      break
    case '放大' :
      cropper.zoom(0.1)
      break
    case '翻转X轴' :
      cropper.scaleX(-cropper.getData().scaleX)
      break
    case '翻转Y轴' :
      cropper.scaleY(-cropper.getData().scaleY)
      break
    case '上移' :
      cropper.move(0, -4)
      break
    case '下移' :
      cropper.move(0, 4)
      break
    case '左移' :
      cropper.move(4, 0)
      break
    case '右移' :
      cropper.move(-4, 0)
      break
  }

}


document.getElementById('size-btn').onclick = function (e) {
  let innerHTML = e.target.innerHTML
  let aspectRatio
  switch (innerHTML) {
    case '自定义' :
      aspectRatio = "自定义"
      disposeActive(e.target)
      break
    case '2:1' :
      aspectRatio = 2 / 1
      disposeActive(e.target)
      break
    case '4:3' :
      aspectRatio = 4 / 3
      disposeActive(e.target)
      break
    case '16:9' :
      aspectRatio = 16 / 9
      disposeActive(e.target)
      break
  }
  if (aspectRatio) {
    console.log(aspectRatio);
    cropper.setAspectRatio(aspectRatio === "自定义" ? '' : aspectRatio)
    // console.log(cropper);
  }
}

